const express = require('express');
const Stock = require('../models/stock');
const StockService = require('../services/stockService');

const router = express.Router();

// 获取所有股票列表
router.get('/stocks', async (req, res) => {
  try {
    let stocks = [];
    try {
      stocks = await Stock.getAllStocks();
    } catch (dbError) {
      console.warn('数据库连接失败，使用缓存数据:', dbError.message);
      // 尝试从StockService的缓存中获取数据
      if (StockService.stockCache && StockService.stockCache.data.size > 0) {
        // 从缓存中获取数据并转换为前端期望的格式
        const cachedStocks = Array.from(StockService.stockCache.data.values());
        stocks = cachedStocks.map((stock, index) => {
          return {
            id: index + 1,
            code: stock.code.replace(/^(sz|sh)/, ''), // 移除市场前缀
            name: stock.name || `股票${stock.code}`
          };
        });
      } else {
        // 使用模拟股票数据
        stocks = [
          { id: 1, code: '000001', name: '平安银行' },
          { id: 2, code: '600036', name: '招商银行' },
          { id: 3, code: '000858', name: '五粮液' }
        ];
      }
    }
    
    // 确保返回的是数组
    if (!Array.isArray(stocks)) {
      console.warn('股票数据不是数组，返回空数组');
      stocks = [];
    }
    
    res.json(stocks);
  } catch (error) {
    console.error('获取股票列表失败:', error);
    // 即使出错也返回空数组而不是错误状态
    res.json([]);
  }
});

// 添加股票
router.post('/stocks', async (req, res) => {
  try {
    const { code, name } = req.body;
    
    if (!code) {
      return res.status(400).json({ error: '股票代码不能为空' });
    }
    
    const stockId = await Stock.addStock(code, name || `股票${code}`);
    
    // 立即获取一次股票数据
    await StockService.updateStockData(code);
    
    res.status(201).json({ id: stockId, code, name: name || `股票${code}` });
  } catch (error) {
    console.error('添加股票失败:', error);
    res.status(500).json({ error: '添加股票失败' });
  }
});

// 删除股票
router.delete('/stocks/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const success = await Stock.deleteStock(id);
    
    if (success) {
      res.json({ message: '股票删除成功' });
    } else {
      res.status(404).json({ error: '股票不存在' });
    }
  } catch (error) {
    console.error('删除股票失败:', error);
    res.status(500).json({ error: '删除股票失败' });
  }
});

// 获取股票的最新价格
router.get('/stocks/:id/price', async (req, res) => {
  try {
    const { id } = req.params;
    let price = null;
    
    try {
      price = await Stock.getLatestPrice(id);
    } catch (dbError) {
      console.warn('数据库连接失败，尝试从缓存获取价格数据:', dbError.message);
      
      // 尝试从StockService的缓存中获取数据
      if (StockService.stockCache && StockService.stockCache.data.size > 0) {
        // 从缓存中查找对应ID的股票
        let stockCode = null;
        
        // 先尝试获取股票代码
        try {
          const stocks = await Stock.getAllStocks();
          const stock = stocks.find(s => s.id == id);
          if (stock) {
            stockCode = stock.code;
          }
        } catch (e) {
          // 如果数据库连接失败，使用模拟数据
          const mockStocks = [
            { id: 1, code: '000001' },
            { id: 2, code: '600036' },
            { id: 3, code: '000858' }
          ];
          const mockStock = mockStocks.find(s => s.id == id);
          if (mockStock) {
            stockCode = mockStock.code;
          }
        }
        
        // 根据股票代码从缓存中获取数据
        if (stockCode) {
          // 格式化股票代码
          if (!stockCode.startsWith('sz') && !stockCode.startsWith('sh')) {
            if (stockCode.startsWith('0') || stockCode.startsWith('3')) {
              stockCode = `sz${stockCode}`;
            } else if (stockCode.startsWith('6')) {
              stockCode = `sh${stockCode}`;
            }
          }
          
          const cachedStock = StockService.stockCache.data.get(stockCode);
          if (cachedStock) {
            // 创建与数据库返回格式相似的对象
            price = {
              stock_id: id,
              price: cachedStock.price,
              open_price: cachedStock.openPrice,
              close_price: cachedStock.closePrice,
              high_price: cachedStock.highPrice,
              low_price: cachedStock.lowPrice,
              timestamp: new Date().toISOString()
            };
          }
        }
      }
    }
    
    if (price) {
      // 设置禁用缓存的HTTP头
      res.set({
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      });
      res.json(price);
    } else {
      res.status(404).json({ error: '未找到价格数据' });
    }
  } catch (error) {
    console.error('获取价格数据失败:', error);
    res.status(500).json({ error: '获取价格数据失败' });
  }
});

// 获取股票的价格历史
router.get('/stocks/:id/history', async (req, res) => {
  try {
    const { id } = req.params;
    const { limit } = req.query;
    const history = await Stock.getPriceHistory(id, limit ? parseInt(limit) : 100);
    res.json(history);
  } catch (error) {
    console.error('获取价格历史失败:', error);
    res.status(500).json({ error: '获取价格历史失败' });
  }
});

// 获取股票的当日价格数据
router.get('/stocks/:id/today', async (req, res) => {
  try {
    const { id } = req.params;
    const prices = await Stock.getTodayPrices(id);
    res.json(prices);
  } catch (error) {
    console.error('获取当日价格数据失败:', error);
    res.status(500).json({ error: '获取当日价格数据失败' });
  }
});

// 手动更新所有股票数据
router.post('/stocks/update', async (req, res) => {
  try {
    await StockService.updateAllStocks();
    res.json({ message: '所有股票数据已更新' });
  } catch (error) {
    console.error('更新股票数据失败:', error);
    res.status(500).json({ error: '更新股票数据失败' });
  }
});

module.exports = router;